#!/usr/bin/env python
#-*- coding: utf-8 -*-

import re
import urllib, urllib2
from cookielib import FileCookieJar
import xmlrpclib

from util import *


def get_poster_by_name(name='CppBlog'):
    return globals()[name + 'Poster']


## ---- FireFox Cookie Jar

class FirefoxCookieJar(FileCookieJar):

    @staticmethod
    def find_ff_cookie_file():
        return r'C:\Documents and Settings\Administrator\Application Data\Mozilla\Firefox\Profiles\omrkzzs9.default\cookies.sqlite'

    def _really_load(self, f, filename, ignore_discard, ignore_expires):
        try:
            import sqlite3 as sqlite
            from cookielib import _warn_unhandled_exception, LoadError, Cookie

            con = sqlite.connect(filename)
            query_str = 'select name, value, host, path, expiry, isSecure from moz_cookies'
            for r in con.execute(query_str):
                name, value, host, path, expires, secure = r

                name = str(name)
                value = str(value) or None
                domain = str(host)
                initial_dot = domain.startswith(".")
                domain_specified = initial_dot
                path = str(path) or None
                path_specified = (path is not None)
                secure = (secure != 0)
                discard = False
                if  not expires:
                    expires = None
                    discard = True

                c = Cookie(0, name, value,
                           None, False,
                           domain, domain_specified, initial_dot,
                           path, path_specified,
                           secure,
                           expires,
                           discard,
                           None,
                           None,
                           {})

                if not ignore_expires and not c.is_expired():
                    self.set_cookie(c)
        except IOError:
            raise
        except Exception:
            _warn_unhandled_exception()
            raise LoadError("invalid Firefox sqlite format cookies file %r" % filename)


## ---- Chrome Cookie Jar

class ChromeCookieJar(FileCookieJar):

    @staticmethod
    def find_ff_cookie_file():
        return r'C:\Documents and Settings\Administrator\Local Settings\Application Data\Google\Chrome\User Data\Default\Cookies'

    def _really_load(self, f, filename, ignore_discard, ignore_expires):
        try:
            import sqlite3 as sqlite
            from cookielib import _warn_unhandled_exception, LoadError, Cookie

            con = sqlite.connect(filename)
            query_str = 'select name, value, host_key, path, expires_utc, secure from cookies'
            for r in con.execute(query_str):
                name, value, host, path, expires, secure = r

                name = str(name)
                value = str(value) or None
                domain = str(host)
                initial_dot = domain.startswith(".")
                domain_specified = initial_dot
                path = str(path) or None
                path_specified = (path is not None)
                secure = (secure != 0)
                discard = False
                if  not expires:
                    expires = None
                    discard = True

                c = Cookie(0, name, value,
                           None, False,
                           domain, domain_specified, initial_dot,
                           path, path_specified,
                           secure,
                           expires,
                           discard,
                           None,
                           None,
                           {})

                if not ignore_expires and not c.is_expired():
                    self.set_cookie(c)
        except IOError:
            raise
        except Exception:
            _warn_unhandled_exception()
            raise LoadError("invalid Chrome sqlite format cookies file %r" % filename)


## ---- Base Poster Class

class Poster(object):
    def login(self, myname, mypwd=None):
        pass

    def postit(self, title, content, category=None):
        pass


## ---- HiBaidu Poster

class HiBaiduPoster(Poster):

    def __init__(self, charset='gb2312'):
        self.HI_PATH = 'http://hi.baidu.com'
        self.charset = charset

    def login(self, myname, mypwd=None):
        self.uid = myname
        self.MY_NAME = urllib.quote_plus(self.uid)
        self.MY_PATH = self.HI_PATH + '/' + self.MY_NAME

        self.cookiejar = ChromeCookieJar(ChromeCookieJar.find_ff_cookie_file())
        self.cookiejar.load()
        self._opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookiejar))
        urllib2.install_opener(self._opener)

    def postit(self, title, content, category=u'默认分类', is_cmt=1, not_public=0):
        tpl = 'ct=1&cm=1&spRefURL=${ref_url}&spBlogTitle=${title}&spBlogText=' + \
                '${content}&spBlogCatName=${category}&spIsCmtAllow=${is_cmt}s' + \
                '&spBlogPower=${not_public}&spVcode=&spVerifyKey=&tj' + \
                '=+%B7%A2%B1%ED%CE%C4%D5%C2+'

        ref_url = self.MY_PATH + '/creat/blog/'

        post_url = self.MY_PATH + '/commit'
        post_data = build_data(tpl, self.charset, ref_url=ref_url, title=title,
                content=content, category=category,
                is_cmt=is_cmt, not_public=not_public
        )

        res = post_helper(post_url, post_data)

        if res:
            ret = safeunicode(ungzip(res), self.charset)
            if re.search(u'发表成功', ret):
                return True
        return False


class CppBlogPoster(Poster):

    def login(self, myname, mypwd=None):
        self.usrname = str(myname)
        self.usrpwd = str(mypwd)
        self.url = 'http://www.cppblog.com/%s/services/metaweblog.aspx' % self.usrname
        self.s = xmlrpclib.ServerProxy(self.url)

        info = self.s.blogger.getUsersBlogs('',
                                            self.usrname, self.usrpwd)
        self.ctx = info[0].copy()
        self.blogid = self.ctx['blogid']

    def postit(self, title, content, category=['Diary']):
        from datetime import datetime

        if isinstance(category, str):
            category = [category]

        post_ctx = {
            'dateCreated' : datetime.now(),
            'description' : content,
            'title' : title,
            'categories' : category,
        }

        ret = self.s.metaWeblog.newPost(self.blogid,
                                  self.usrname, self.usrpwd,
                                  post_ctx, True)

        return ret


## ---- mainline

if __name__ == '__main__':
    hi = CppBlogPoster()
    hi.login('fanxes', '159632')
    print hi.postit(u'[Google Api 中文版]', u'hi 中文 123')

